<script setup lang="ts">
import { ContentWrapNoHeaderLine } from '@/components/ContentWrap'
import { useIcon } from '@/hooks/web/useIcon'
import { Table } from '@/components/Table'
import {
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElButton,
  ElSpace,
  ElDivider,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElCheckbox, ElMessageBox, ElMessage
} from 'element-plus'
import { reactive, ref, h, watch } from 'vue'
import { useTable } from "@/hooks/web/useTable";
import { PanData } from "@/api/snapshot/pan/types";
import { OrgData } from '@/api/org/types'
import { getSelectOrgListApi } from "@/api/org/index";
import { getPanListApi, backPanApi, checkPanApi, delPanApi } from "@/api/snapshot/pan/index";
import { Pagination, TableColumn } from "@/types/table";

const queryModel = reactive<Recordable>({
  companyId: '',
  userId: ''
})

const columns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: '操作编号',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'file_total',
    label: '文件目录总数',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'total_space',
    label: '空间总量',
    visible: true,
    className: ''
  }, {
    field: 'used_space',
    label: '已使用量',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'occupancy_space',
    label: '占用空间',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'data_ids',
    label: '秘文端编号',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'name',
    label: '名称',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'action',
    label: '操作',
    visible: true,
    className: ''
  }
])

const { register, tableObject, methods } = useTable<PanData>({
  getListApi: getPanListApi,
  delListApi: delPanApi,
  response: {
    list: 'list',
    total: 'total'
  }
})
const paginationObj = ref<Pagination>()
watch(() => tableObject.total,
  (val) => {
    if (val > 0) {
      paginationObj.value = {
        total: tableObject.total
      }
    } else {
      paginationObj.value = undefined
    }
  })
const { getList, setSearchParams } = methods
getList()

const icons = {
  plusIcon: useIcon({ icon: 'ph:plus-bold' }),
  deleteIcon: useIcon({ icon: 'ep:delete' })
}
const spacer = h(ElDivider, { direction: 'vertical' })

const handleQuery = () => {
  setSearchParams({ ...queryModel })
}

const selectedCount = ref(0)
const multipleSelection = ref<PanData[]>([])
const handleSelectionChange = (val: PanData[]) => {
  multipleSelection.value = val
  selectedCount.value = val?.length || 0
}

const handleVisibleChange = (item) => {
  item.className = item.visible ? '' : 'hidden'
}

const delLoading = ref(false)

const handleCheckButton = (row: PanData) => {
  tableObject.currentRow = row
  ElMessageBox.confirm("确认验证吗？", '', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: 'warning'
  }).then(async () => {
    checkPanApi(row).then(res => {
      console.log(res)
      ElMessage.success("操作成功！");
    })
  }).catch(() => {
    console.log("取消操作");
  })
}
const handleBackButton = (row: PanData) => {
  tableObject.currentRow = row
  ElMessageBox.confirm("确认回退吗？", '', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: 'warning'
  }).then(async () => {
    backPanApi(row).then(res => {
      console.log(res)
      ElMessage.success("操作成功！");
    })
  }).catch(() => {
    console.log("取消操作");
  })
}
const handleDeleteButton = async (row: PanData | null, multiple: boolean) => {
  tableObject.currentRow = row
  const { delListByObj, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delListByObj(
    multiple ? selections : [row] as PanData[],
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}
const companyList = ref([] as OrgData[]);
getSelectOrgListApi().then(res => {
  companyList.value = res.data
})
</script>

<template>
  <ContentWrapNoHeaderLine title="虚拟盘快照">
    <div class="flex justify-between">
      <el-form :inline="true" ref="queryFormRef" :model="queryModel">
        <el-form-item>
          <el-space direction="horizontal" :size="0">
            <el-select v-model="queryModel.companyId" placeholder="请选择组织机构">
              <el-option v-for="item in companyList" :label="`${item.name}`" :key="item.companyId"
                :value="`${item.companyId}`" />
            </el-select>
            <el-input v-model="queryModel.userId" placeholder="沙箱ID">
              <template #append>
                <el-button class="query-button" type="primary" @click="handleQuery">查询</el-button>
              </template>
            </el-input>
          </el-space>
        </el-form-item>
      </el-form>
    </div>
    <div class="rounded bg-gray-100 w-full flex justify-between px-1.5 py-2 mb-3.5">
      <el-space :size="10" :spacer="spacer">
        <div>已批量选择<span class="mx-1 text-[var(--el-color-primary)]">{{ selectedCount }}</span>条事项</div>
        <el-button :icon="icons.deleteIcon" link @click="handleDeleteButton(null, true)">批量删除</el-button>
      </el-space>
      <el-space :size="10">
        <el-dropdown trigger="click" :hide-on-click="false">
          <span class="el-dropdown-link">
            <Icon icon="icon-park-outline:config" class="cursor-pointer " />
          </span>
          <template #dropdown>
            <div class="flex flex-col p-2">
              <template v-for="column in columns">
                <el-checkbox v-if="column.field !== 'action'" v-model="column.visible" :label="column.label"
                  :key="column.field" size="small" @change="handleVisibleChange(column)" />
              </template>
            </div>
          </template>
        </el-dropdown>
        <el-dropdown trigger="click">
          <span class="el-dropdown-link">
            <Icon icon="bi:download" class="cursor-pointer " />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>导出到Csv</el-dropdown-item>
              <el-dropdown-item>导出到Excle</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <Icon icon="bi:printer" class="cursor-pointer " />
      </el-space>
    </div>
    <div class="">
      <Table border v-model:pageSize="tableObject.page_size" v-model:currentPage="tableObject.page_index"
        :columns="columns" :data="tableObject.tableList" :loading="tableObject.loading" :pagination="paginationObj"
        @register="register" @select="handleSelectionChange" @select-all="handleSelectionChange">
        <template #action="{ row }">
          <el-space :size="6" :spacer="spacer">
            <ElButton type="primary" link @click="handleDeleteButton(row, false)">
              删除
            </ElButton>
            <ElButton type="primary" link @click="handleCheckButton(row)">
              验证
            </ElButton>
            <ElButton type="primary" link @click="handleBackButton(row)">
              回退
            </ElButton>
          </el-space>
        </template>
      </Table>
    </div>
  </ContentWrapNoHeaderLine>
</template>
